const fs = require('fs'); //导入/加载/引入 文件模块
const queryString = require('querystring');
const sendMail = require('./../public/js/sendMail.js');
const opeSql = require('./../model/sql.js');
const noteController = require(process.cwd() + '/controller/note_control.js');

module.exports = function onRequest(req, res) {
    let pathName = req.url;
    if (pathName === '/') {// 默认打开欢迎页
        originPageLoad(res);
    } else if (pathName.endsWith(".html")) {// 表示是页面
        readHtml(pathName, res);
    } else if (pathName.startsWith('/api')) {// 表示是接口
        let apiName = pathName.slice(5);
        postRequest(req, res, apiName);
    } else if (pathName.startsWith('/public')) {// 表示是资源文件
        readResource(pathName, res);
    } else if (pathName.indexOf('/edit') === 0 || pathName.indexOf('/single-note') === 0 ||
        pathName.indexOf('/notebook') === 0 || pathName.indexOf('/modify-note') === 0 ||
        pathName.indexOf('/find-note') === 0 || pathName.indexOf('/delete-note') === 0 ||
        pathName.indexOf('/add-tag') === 0) {// 国伟兄弟的代码
        noteModuleDeal(req, res, pathName);
    }
}

// 初始页面跳转
function originPageLoad(res) {
    //8. 读取文件index.html
    fs.readFile('./view/other/welcome.html', 'utf-8', (err, data) => {
        if (err) {
            return console.log(err);
        }
        // end方法返回读取的文件字符串，浏览器会显示该文件内容
        res.end(data);
    })
}

// 读取HTML文件
function readHtml(pathName, res) {
    //8. 读取html文件
    fs.readFile('.' + pathName, 'utf-8', (err, data) => {
        if (err) {
            return console.log(err);
        }
        res.end(data);
    })
}

// 读取资源文件
function readResource(pathName, res) {
    fs.readFile('.' + pathName, (err, data) => {
        if (err) {
            return console.log(err);
        }
        res.end(data);
    })
}

// 国伟兄弟的模块
function noteModuleDeal(req, res, currentUrl) {
    if (currentUrl.indexOf('/edit') === 0) {
        fs.readFile('./view/note-program/edit.html', 'utf8', function (err, data) {
            if (err) res.end('404 Not Found');
            var book_title = '', note_title = '';
            let arr = currentUrl.split('?');
            let url = queryString.parse(arr[1]);
            if (url['note_title'] != undefined) {
                book_title = url.book_title;
                note_title = url.note_title;
                let text = '';
                let promise = new Promise(async (resolve, reject) => {
                    await noteController.initNote(book_title, note_title);
                    resolve('get_success');
                }).then(() => {
                    let html = `<textarea style="display:none;">${global.text}</textarea>`;
                    data = data.replace('<textarea style="display:none;"></textarea>', html);
                    res.end(data);
                })
            } else res.end(data);
        })
    } else if (currentUrl.indexOf('/notebook') === 0) {
        if (req.method == 'POST') noteController.create(req, res);
        else if (req.method == 'OPTIONS') noteController.update(req, res);
        else noteController.openNotebook(req, res);
    } else if (currentUrl.indexOf('/single-note') === 0) {
        if (req.method == 'POST') noteController.addNote(req, res);
        else if (req.method == 'GET') noteController.viewNote(req, res);
    } else if (currentUrl.indexOf('/modify-note') === 0) {
        if (req.method == 'POST') noteController.modifyNote(req, res);
        else if (req.method == 'GET') noteController.verifyNote(req, res);
    } else if (currentUrl.indexOf('/find-note') === 0) {
        if (req.method == 'GET') noteController.findNote(req, res);
    } else if (currentUrl.indexOf('/delete-note') === 0) {
        if (req.method == 'GET') noteController.deleteNote(req, res);
    } else if (currentUrl.indexOf('/add-tag') === 0) {
        if (req.method == 'GET') noteController.addTag(req, res);
    } else {
        //否则404
        fs.readFile('./view/note-program/404.html', 'utf8', function (err, data) {
            if (err) res.end('404 Not Found');
            res.end(data)
        })
    }
}

// POST请求
function postRequest(req, res, workName) {
    let body = "";
    req.on('data', function (chunk) {
        body += chunk;
    });
    req.on('end', function () {
        // 解析参数
        body = queryString.parse(body);
        dealBusiness(body, req, res, workName);
    });
}

// 业务逻辑处理
function dealBusiness(body, req, res, workName) {
    // 根据业务名称处理对应的业务
    if (workName == 'modifyPsw') {
        modifyPsw(body, res);
    } else if (workName == 'modifyName') {
        modifyName(body, res);
    } else if (workName == 'userRegister') {
        userRegister(body, res);
    } else if (workName == 'emailLogin') {
        emailLogin(body, res);
    } else if (workName == 'sendEmail') {
        sendEmail(body, res);
    } else if (workName == 'pswLogin') {
        pswLogin(body, res);
    } else if (workName == 'pswLogin') {
        pswLogin(body, res);
    }
}

// 修改密码
function modifyPsw(body, res) {
    // 去数据库里查询该email是否存在，如果存在则返回200
    let where = {"email": body.email};
    let update = {$set: {"password": body.password}};
    opeSql.updateSql('user_message', where, update).then(val => {
        let data = {
            "statusCode": 400,
            "msg": "修改密码失败"
        }
        if (val == '更新成功') {
            data.statusCode = 200;
            data.msg = "修改密码成功";
        }
        res.end(JSON.stringify(data));
    });
}

// 修改用户名
function modifyName(body, res) {
    // 去数据库里查询该email是否存在，如果存在则返回200
    let where = {"email": body.email};
    let update = {$set: {"username": body.name}};
    opeSql.updateSql('user_message', where, update).then(val => {
        let data = {
            "statusCode": 400,
            "msg": "修改昵称失败"
        }
        if (val == "更新成功") {
            data.statusCode = 200;
            data.msg = "修改昵称成功";
        }
        res.end(JSON.stringify(data));
    });
}

// 用户注册
function userRegister(body, res) {
    let sql = {"username": body.userName, "email": body.email, "password": body.password};
    opeSql.insertSql('user_message', sql).then(val => {
        //将邮箱和密码存入数据库
        let data = {
            "statusCode": 400,
            "msg": "注册失败"
        }
        if (val == '添加成功') {
            data.statusCode = 200;
            data.msg = "注册成功";
        }
        res.end(JSON.stringify(data));
    });
}

// 邮箱登录
function emailLogin(body, res) {
    let sql = {"email": body.email};
    opeSql.querySql('user_message', sql).then(val => {
        // 去数据库里查询该email是否存在，如果存在则返回200
        let data = {
            "statusCode": 400,
            "msg": "查询结果为空"
        }
        if (val != '[]' && val != "查询失败") {
            data.statusCode = 200;
            data.msg = "查询结果成功";
        }
        res.end(JSON.stringify(data));
    });
}

// 发送邮件
function sendEmail(body, res) {
    let email = body.email;
    // 生成验证码
    let verCode = "";
    for (let i = 0; i < 6; i++) {
        verCode += Math.floor(Math.random() * 10);
    }
    let result = sendMail(email, verCode);
    let data = {
        "statusCode": 200,
        "msg": "发送成功",
        "data": {
            "verCode": verCode
        }
    }
    if (result === 0) {//表示邮件发送失败
        data.statusCode = 400;
        data.msg = "发送失败";
        data.data.verCode = null;
    }
    res.end(JSON.stringify(data));
}

// 密码登录
function pswLogin(body, res) {
    let data = {
        "statusCode": 400,
        "msg": "该用户不存在"
    }
    let sql = {$and: [{"email": body.email}, {"password": body.password}]};
    opeSql.querySql('user_message', sql).then(val => {
        console.log(val);
        if (val != '[]' && val != "查询失败") {
            data.statusCode = 200;
            data.msg = "该用户存在";
        }
        res.end(JSON.stringify(data));
    });
}

// 沈晓伟同学的代码
function dealOtherMouble(req, res) {
    // post
    let reqBody = '';
    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量
    req.on('data', function (data) {
        reqBody += data;
    });
    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
    req.on('end', function () {    //req完成后处理数据并返回
        reqBody = JSON.parse(reqBody);
        //查询数据库并获取资源然后返回
        switch (reqBody.type) {
            case 'square':    //初始化数据请求
                queryData(reqBody, res, 'square');
                break;
            case 'userPost':
                queryData(reqBody, res, 'square');
                break;
            case 'detailContent':
                queryData(reqBody, res, 'comments');
                break;
        }

    })
}

function queryData(req, res, collection) {
    opeSql.squareSql(req, res, collection);
}

